<template>
  <div>
    <h1>用户管理</h1>
    <el-table :data="userList" :border="true">
      <el-table-column label="用户id" prop="user_id"></el-table-column>
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column label="性别" prop="gender"></el-table-column>
      <el-table-column label="年龄" prop="age"></el-table-column>
      <el-table-column>
        <template #default="{row}">
          <el-button @click="handleDelete(row)" type="danger" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @current-change="handleCurrentChange"
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="total"
    >
    </el-pagination>
  </div>
</template>
<script>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from '../axios';

export default {
  name: 'UserManagement',
  setup() {
    const userList = ref([]);
    const currentPage = ref(1);
    let pageSize = 10;
    const total = ref(0);
    const token = localStorage.getItem('token');

    const getUserList = async () => {
      axios.get('./getUserList', {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'multipart/form-data'
            }
          })
        .then(response => {
          userList.value = response.data.userList;
        })
        .catch(error => {
          console.error(error);
        });
    }

    const handleDelete = async (row) => {
        try {
          const response = await axios.delete('./delUser', {
              headers: {
                'Authorization': `Bearer ${token}`,
              },
              params: {
                id: row.user_id
              }
            }
          );
          if (response.data.success) {
            ElMessage.success(response.data.message);
            getUserList();
          } else {
            ElMessage.error(response.data.message);
            window.location.reload();
          }
        } catch (error) {
          console.error(error);
          ElMessage.error(error);
        }
      };
      const handleCurrentChange = (val) => {
          currentPage.value = val;
          getUserList();
      };

    onMounted(() => {
      getUserList();
    });

    

    return { 
      userList,
      getUserList,
      handleDelete,
      currentPage,
      pageSize,
      total,
      handleCurrentChange
    };
  }
}
</script>

<style>
h1 {
  font-size: 24px;
  margin-bottom: 10px;
}

ul {
  list-style: none;
}

li {
  padding: 5px;
  margin-bottom: 5px;
  border: 1px solid #ccc;
}
</style>